package com.chj.controller;

import com.chj.vo.Product;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * 通过restTemplate访问product服务
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerProductSecurityController {
    public static final String PRODUCT_TOPIC = "SPRINGCLOUD-MICRO-PRODUCT";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private HttpHeaders httpHeaders;
    // 服务提供方的信息获取
    @Resource
    private LoadBalancerClient loadBalancerClient;
    /**
     * 添加了spring security以后，访问接口需要密码验证，需要在请求头HttpHeaders中添加验证信息
     */
    @RequestMapping("/product/list3")
    public  Object listProduct3() {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose(PRODUCT_TOPIC) ;
        System.out.println("【*** ServiceInstance ***】host = " + serviceInstance.getHost()
                + "：port = " + serviceInstance.getPort() +"：serviceId = " +serviceInstance.getServiceId());
        URI uri = URI.create(String.format("http://%s:%s/prodcut/list/", serviceInstance.getHost(), serviceInstance.getPort()));
        List<Product> list = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders), List.class).getBody();
        return  list;
    }
}